package com.platform.qujia.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.google.gson.Gson;
import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.dao.PayOrderMapper;
import com.platform.qujia.enums.PayWayServiceChargeEnum;
import com.platform.qujia.param.request.RechargeBalance;
import com.platform.qujia.pay.strategy.YunhuaChannel;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.DivideAccountsSettingDto;
import com.platform.qujia.pojo.dto.PhysicalCardOrderDto;
import com.platform.qujia.pojo.dto.PhysicalCardSecretKeyDto;
import com.platform.qujia.service.AppUserInfoService;
import com.platform.qujia.service.EnterpriseService;
import com.platform.qujia.service.PhysicalCardBalanceService;
import com.platform.qujia.service.PhysicalCardService;
import com.platform.qujia.utils.*;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.jinkong.JKPayUtil;
import com.platform.qujia.utils.sxfpay.SXFPayParam;
import com.platform.qujia.utils.sxfpay.SXFPayUtil;
import com.platform.qujia.utils.yunHua.YunHuaParam;
import com.platform.qujia.utils.yunHua.yunHuaPayUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/physicalCard")
@Slf4j
@Api("储值卡使用")
public class PhysicalCardController {

    @Autowired
    private PhysicalCardService physicalCardService;

    @Autowired
    private PhysicalCardBalanceService physicalCardBalanceService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Resource
    private PayOrderMapper payOrderMapper;

    @Autowired
    private AppUserInfoService appUserInfoService;

    @Value("${qujia.yunhuaPrePayUrl}")
    private String yunHuaPrePayUrl;

    @Value("${qujia.domainName}")
    private String domainName;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${physicalCard.secretKeyA}")
    private String SECRET_KEY_A;

    @Value("${physicalCard.secretKeyB}")
    private String SECRET_KEY_B;

    @Value("${physicalCard.external.publicKey}")
    private String publicKey;

    @Value("${physicalCard.external.privateKey}")
    private String privateKey;

    @Value("${physicalCard.external.message}")
    private String messageKey;

    @GetMapping("/bind/appUser")
    @ApiOperation("会员绑定储值卡")
    public ResultData physicalCardBindAppUser(@RequestParam("physicalCardNo") String physicalCardNo,
                                              @RequestParam("userPhone") String userPhone,
                                              @RequestParam("userId") Integer appUserId){
        if(Objects.isNull(appUserId) || StringUtils.isEmpty(physicalCardNo) || StringUtils.isEmpty(userPhone)){
            return ResultData.error("请求参数异常");
        }
        physicalCardService.physicalCardBindAppUser(physicalCardNo,userPhone,appUserId);
        return ResultData.success();
    }

    @PostMapping("/account/recharge")
    @ApiOperation("储值卡微信充值")
    public ResultData physicalCardWxRecharge(@RequestBody PhysicalCardBalance physicalCardBalance){
        if(Objects.isNull(physicalCardBalance) || StringUtils.isEmpty(physicalCardBalance.getPhysicalCardNo())){
            return ResultData.error("请求参数异常");
        }

        if(StringUtils.isEmpty(physicalCardBalance.getStationId())){
            return ResultData.error("当前油站不存在");
        }
        if(Objects.isNull(physicalCardBalance.getAmount()) || physicalCardBalance.getAmount().compareTo(BigDecimal.ZERO)<=0){
            return ResultData.error("充值金额不合理");
        }
        PhysicalCardBalance balance = physicalCardBalanceService.physicalCardWxRecharge(physicalCardBalance);
        return ResultData.success(balance.getBalanceNo());
    }

    //储值卡公众号充值拉起第三方支付
    @RequestMapping(value = "/rechargeToThirdPayment", method = RequestMethod.POST)
    @ApiOperation(value = "储值卡公众号充值拉起第三方支付", httpMethod = "POST", notes = "储值卡公众号充值拉起第三方支付")
    public String rechargeToThirdPayment(@RequestBody RechargeBalance rechargeBalance) throws Exception {
        Gson gson = new Gson();
        ResultData resultData = null;
        if(rechargeBalance !=null && org.apache.commons.lang3.StringUtils.isNotBlank(rechargeBalance.getAmt()) && org.apache.commons.lang3.StringUtils.isNotBlank(rechargeBalance.getOpenId())
                && org.apache.commons.lang3.StringUtils.isNotBlank(rechargeBalance.getUserType()) && rechargeBalance.getStationId() !=null && org.apache.commons.lang3.StringUtils.isNotBlank(rechargeBalance.getOrderNo())) {
            //String amt = rechargeBalance.getAmt();
            String openId = rechargeBalance.getOpenId();    //公众号的openId
            Integer stationId = rechargeBalance.getStationId();

            String userType = "1";
            String ordNo = rechargeBalance.getOrderNo();
//            CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
//            customerCardUseRecord.setOrderNo(ordNo);
//            CustomerCardUseRecord cardRecordByOrderNo = electronicMembershipCardService.getCardRecordByOrderNo(customerCardUseRecord);

            PhysicalCardBalance balance = new PhysicalCardBalance();
            balance.setBalanceNo(ordNo);
            PhysicalCardBalance physicalCardBalance = physicalCardBalanceService.selectPhysicalCardBalance(balance);
            PhysicalCard physicalCard = physicalCardService.selectByPhysicalCardByNo(physicalCardBalance.getPhysicalCardNo());
            if(Objects.isNull(physicalCard) || Objects.isNull(physicalCard.getAppUserId())){
                resultData = ResultData.error("实体卡未绑定会员");
                return gson.toJson(resultData);
            }

            if(physicalCardBalance !=null ){
                if(physicalCardBalance.getStatus() !=null && physicalCardBalance.getStatus().equals("0")){

//                    PayWay payWayForm=new PayWay();
//                    payWayForm.setUseType(PayWayUseTypeEnum.RECHARGE.getValue().toString());             //使用类型
//                    payWayForm.setStationId(Integer.valueOf(physicalCardBalance.getStationId()));
//                    payWayForm.setAppType(PayWayServiceChargeEnum.APPTYPE_WECHAT.getValue().toString());
//                    PayWay payWay = payWayMapper.getOneStationPayWay(payWayForm); //获取该油站的支付类型，默认找微信的
//                    if (payWay == null || payWay.getServiceCharge() == null) {
//                        throw new CustomException("找不到微信支付渠道");
//                    }

                    //获取油站的支付配置项信息
                    PayWay payWay = new PayWay();

                    payWay.setStationId(Integer.valueOf(stationId));
                    payWay.setAppType(PayWayServiceChargeEnum.APPTYPE_WECHAT.getValue().toString());        //支付宝还是微信
                    payWay.setUseType("0");  //使用类型 userType = 0 是充值 1 是消费
                    //获取该油站的支付类型
                    List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay);
                    HashMap<String, Object> resultMap = new HashMap<>();
                    if(payWayList !=null && payWayList.size() == 1){
                        payWay = payWayList.get(0);
                        if(payWay.getServiceCharge() != null){
                            BigDecimal sc = physicalCardBalance.getAmount().multiply(payWay.getServiceCharge()).multiply(DecimalConstant.O_001).setScale(2, RoundingMode.HALF_UP);
                            physicalCardBalance.setServiceCharge(sc);
                        }
                        physicalCardBalance.setPayWayId(payWay.getPayWayId().longValue());
                        PhysicalCardBalance update = new PhysicalCardBalance();
                        update.setId(physicalCardBalance.getId());
                        update.setPayWayId(physicalCardBalance.getPayWayId());
                        update.setServiceCharge(physicalCardBalance.getServiceCharge());
                        physicalCardBalanceService.updateById(update);
                        //当前油站的支付方式 是随行付还云闪付
                        String payTypeSta = payWay.getPayType();
                        String mno = payWay.getMno();    //商户号
                        String cardName ="";

                        switch (physicalCard.getCardType()){
                            case "0":
                                cardName = "通用";
                                break;
                            case "1":
                                cardName = "汽油";
                                break;
                            case "2":
                                cardName = "柴油";
                                break;
                            case "3":
                                cardName = "LNG";
                                break;
                            case "4":
                                cardName = "CNG";
                                break;
                        }
                        String subject = cardName+ "储值卡" + " - " +physicalCardBalance.getStationName();
                        String notifyUrl = "";
                        //公众号
                        String appId  = payWayList.get(0).getEnterprise().getGzhAppId();


                        String userId="";
//                        List<AppUserInfo> appUserInfos=appUserInfoService.selectAppUserInfoByMobilePhoneAndStationId(AppUserInfo.builder().mobilePhone(cardRecordByOrderNo.getMobilePhone()).stationId(payWayList.get(0).getEnterpriseId()).build());
//                        if(appUserInfos!=null&&appUserInfos.size()>0){
//                            if(appUserInfos.get(0).getYunhuaUserId()!=null){
//                                userId=appUserInfos.get(0).getYunhuaUserId();
//                            }else {
//                                userId=appUserInfos.get(0).getMobilePhone();
//                            }
//                        }
                        AppUserInfo appUserInfo = new AppUserInfo();
                        appUserInfo.setUserId(physicalCard.getAppUserId());
                        AppUserInfo userInfo = appUserInfoService.getAppUserInfo(appUserInfo);
                        if(Objects.nonNull(userInfo)){
                            if(userInfo.getYunhuaUserId()!=null){
                                userId = userInfo.getYunhuaUserId();
                            }else {
                                userId = userInfo.getMobilePhone();
                            }
                        }

                        switch (payTypeSta){
                            case "1":   //随行付
                                SXFPayParam sxfPayParam = new SXFPayParam();
                                sxfPayParam.setAmt(physicalCardBalance.getAmount().toString());
                                sxfPayParam.setAppId(appId);
                                sxfPayParam.setMno(mno);
                                sxfPayParam.setOrdNo(ordNo);
                                //notifyUrl = "https://"+domainName+"/" +"apipay/physicalCard/suiXinFuCard";
                                notifyUrl = "https://"+domainName+"/" + contextPath+"/physicalCard/suiXinFuCard";
                                sxfPayParam.setNotifyUrl(notifyUrl);
                                sxfPayParam.setSubject(subject);
                                sxfPayParam.setUserId(openId);
                                sxfPayParam.setUserType(userType);
                                sxfPayParam.setWeChatType("2");

                                String ledgerAccountFlag = "0";

                                sxfPayParam.setLedgerAccountFlag(ledgerAccountFlag);
                                resultMap = SXFPayUtil.tradeJsApiScan(sxfPayParam);
                                resultMap.put("merchantsNumber","111111");
                                break;
                            case "5":   //云华支付
                                notifyUrl = "https://" + domainName + contextPath + "/physicalCard/yunHuaCard";

                                log.info("储值卡充值单号为"+physicalCardBalance.getBalanceNo()+"");
//                                resultMap = yunHuaPayUtils.yunHuaPay(YunHuaParam.builder()
//                                        .clientOrgCode(payWayList.get(0).getMno())
//                                        .lockFlag("lock")
//                                        .noticeUrl(notifyUrl)
//                                        .partnerCode(payWayList.get(0).getTerminalNo())
//                                        .payChannelId("wx_jsapi")
//                                        .posOrderNo(ordNo)
//                                        .reqTime(nowdate)
//                                        .txnAmt(cardRecordByOrderNo.getAmt())
//                                        .vsOrderNo(ordNo)
//                                        .openId(openId)
//                                        .carRefueling(nowdate)
//                                        .build());
                                String txnDesc = "实体卡充值";
                                resultMap= yunHuaPayUtils.yunHuaPayV2(YunHuaParam.builder()
                                        .partnerCode(payWayList.get(0).getMno())
                                        .posOrderNo(ordNo)
                                        .txnDesc(txnDesc)
                                        .noticeUrl(notifyUrl)
                                        .txnAmt(physicalCardBalance.getAmount())
                                        .userId(userId)
                                        .build(),payWayList.get(0).getSecretKey(),yunHuaPrePayUrl);
                                resultMap.put("merchantsNumber","111111");
                                break;
                        }
                        resultMap.put("thirdPayment", payTypeSta);
//                        String merchantsNumber ="";
//                        if(resultMap.containsKey("merchantsNumber")){
//                            merchantsNumber = resultMap.get("merchantsNumber").toString();
//                        }
//                        electronicMembershipCardService.updateCardRecordStatusByOrderNo(CustomerCardUseRecord.builder()
//                                .merchantsNumber(merchantsNumber)
//                                .orderNo(ordNo).build());
                        resultData = ResultData.success(resultMap);
                    }else {
                        resultData = ResultData.error(CodeMsg.NOT_PAYWAY);
                    }
                }else {
                    resultData = ResultData.error(CodeMsg.ALREADY_PAY);
                }
            }else {
                resultData=ResultData.error(CodeMsg.YEWU_FAIL,"未查询到订单");
            }
        }
        log.info("rechargeToThirdPayment储值卡拉起第三方支付方式：[{}]", JSONObject.toJSONString(resultData));
        return gson.toJson(resultData);
    }


    /**
     * 储值卡随行付回调接口
     * */
    @RequestMapping(value = "/suiXinFuCard", consumes = "application/json", method = RequestMethod.POST)
    public JSONObject suiXinFuCard(@RequestBody JSONObject request) throws ParseException {
        log.info("=========================实体卡充值功能随行付回调功能===============================");
        log.info("实体卡充值功能随行付回调返回过来的参数："+request);

        Gson gson =new Gson();
        String sxfUuid=request.get("sxfUuid").toString();     //随行付落单号
        String payWay=request.get("payWay").toString();     //随行付交易方式
        String payTime=request.get("payTime").toString();   //随行付交易时间
        String uuid=request.get("uuid").toString();         //随行付交易流水号
        String mno=request.get("mno").toString();//发起交易的商户编号
        String ordNo=request.get("ordNo").toString();//商户生成的订单号
        String amt=request.get("amt").toString();//金额
        String buyerId=request.get("buyerId").toString();//用户登录
        String transactionId=request.get("transactionId").toString();//用户登录
        String drType=request.get("drType").toString();//借贷记标识 1-借,2-贷，3-其他
        String payType=request.get("payType").toString();//对订单的描述，取值范围：WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
        String payBank=request.get("payBank").toString();//付款银行银行编码，例如 ICBC
        String pointAmount=request.get("pointAmount").toString();//代金券金额
        String totalOffstAmt=request.get("totalOffstAmt").toString();//消 费 者 付 款金额
        String settleAmt=request.get("settleAmt").toString();//商家入账金额
        String timeStamp=request.get("timeStamp").toString();//响应时间
        String sign=request.get("sign").toString();//签名
        String bizCode=request.get("bizCode").toString();//业务返回码
        String bizMsg=request.get("bizMsg").toString();//业 务 返 回 信息
        String openid=request.get("openid").toString();//微 信 或 支 付宝身份id()opendid userid
        String channelId=request.get("channelId").toString();//渠道商户号
        String subMechId=request.get("subMechId").toString();//子商户号
        String finishTime=request.get("finishTime").toString();//交易完成时间
        String clearDt=request.get("clearDt").toString();
        String settlementBatchNo=request.get("settlementBatchNo").toString();
        //String origOrdNo=request.get("origOrdNo").toString();//反交易退款异步通知
        //String origUuid=request.get("origUuid").toString();//token
        //String scene=request.get("scene").toString();//用户登录
        //String buyerAccount=request.get("buyerAccount").toString();//
        //String realRefundAmount=request.get("realRefundAmount").toString();//商家出账金额
        //String recFeeAmt=request.get("recFeeAmt").toString();//交易手续费
        //String recFeeRate=request.get("recFeeRate").toString();//交易手续费率
        //String refBuyerAmt=request.get("refBuyerAmt").toString();//消 费 者 到 账金额
        String extend =request.containsKey("extend") ? request.getString("extend") : null;//备用

        //将业务参数存放在 JSON 对象中
        JSONObject reqData = new JSONObject();

        //支付场景
        if(request.containsKey("scene") && request.get("scene") !=null){
            String scene = request.get("scene").toString();
            reqData.put("scene", scene);
        }

        //recFeeRate
        if(request.containsKey("recFeeRate") && request.get("recFeeRate") !=null){
            String recFeeRate = request.get("recFeeRate").toString();
            reqData.put("recFeeRate", recFeeRate);
        }

        //消 费 者 到 账金额
        if(request.containsKey("refBuyerAmt") && request.get("refBuyerAmt") !=null){
            String refBuyerAmt = request.get("refBuyerAmt").toString();
            reqData.put("refBuyerAmt", refBuyerAmt);
        }

        //buyerAccount 支付宝买家登录账号  掩码；示例：135***1234
        if(request.containsKey("buyerAccount") && request.get("buyerAccount") !=null){
            String buyerAccount = request.get("buyerAccount").toString();
            reqData.put("buyerAccount", buyerAccount);
        }

        //备用
        if(request.containsKey("extend") && request.get("extend") !=null){
            String extend1 = request.get("extend").toString();
            reqData.put("extend", extend1);
        }
        //优惠券参数
        if(request.containsKey("promotionDetail") && request.get("promotionDetail") !=null){
            String promotionDetail = request.get("promotionDetail").toString();
            reqData.put("promotionDetail", promotionDetail);
        }
        //商家出账金额
        if(request.containsKey("realRefundAmount") && request.get("realRefundAmount") !=null){
            String realRefundAmount = request.get("realRefundAmount").toString();
            reqData.put("realRefundAmount", realRefundAmount);
        }
        //szltFlag
        if(request.containsKey("szltFlag") && request.get("szltFlag") !=null){
            String szltFlag = request.get("szltFlag").toString();
            reqData.put("szltFlag", szltFlag);
        }
        //recFeeAmt
        if(request.containsKey("recFeeAmt") && request.get("recFeeAmt") !=null){
            String recFeeAmt = request.get("recFeeAmt").toString();
            reqData.put("recFeeAmt", recFeeAmt);
        }
        //szltRecfeeAmt
        if(request.containsKey("szltRecfeeAmt") && request.get("szltRecfeeAmt") !=null){
            String szltRecfeeAmt = request.get("szltRecfeeAmt").toString();
            reqData.put("szltRecfeeAmt", szltRecfeeAmt);
        }

        reqData.put("sxfUuid",sxfUuid);
        reqData.put("payWay",payWay);
        reqData.put("payTime",payTime);
        reqData.put("uuid",uuid);
        reqData.put("mno",mno);
        reqData.put("ordNo",ordNo);
        reqData.put("amt",amt);
        reqData.put("buyerId",buyerId);
        reqData.put("transactionId",transactionId);
        reqData.put("drType",drType);
        reqData.put("payType",payType);
        reqData.put("payBank",payBank);
        reqData.put("pointAmount",pointAmount);
        reqData.put("totalOffstAmt",totalOffstAmt);
        reqData.put("settleAmt",settleAmt);
        reqData.put("timeStamp",timeStamp);
        reqData.put("bizCode",bizCode);
        reqData.put("bizMsg",bizMsg);
        reqData.put("openid",openid);
        reqData.put("channelId",channelId);
        reqData.put("subMechId",subMechId);
        reqData.put("finishTime",finishTime);
        reqData.put("clearDt",clearDt);
        reqData.put("settlementBatchNo",settlementBatchNo);
        //reqData.put("realRefundAmount",realRefundAmount);
        //reqData.put("recFeeAmt",recFeeAmt);
        //reqData.put("recFeeRate",recFeeRate);
        //reqData.put("buyerAccount",buyerAccount);
        //reqData.put("origOrdNo",origOrdNo);
        //reqData.put("origUuid",origUuid);
        //reqData.put("scene",scene);
        //reqData.put("refBuyerAmt",refBuyerAmt);
        //reqData.put("extend",extend);

        //根据回调信息，先进行验签，验签后修改状态
        log.info("打印参数信息"+gson.toJson(reqData));
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(gson.toJson(reqData), LinkedHashMap.class, Feature.OrderedField);
        //验签
        String resultStr = RSASignature.getOrderContent(result);
        JSONObject req = new JSONObject();
//        if (RSASignature.doCheck(resultStr, sign, SXFPaySign.sxfPublic)) {
        req.put("code","success");
        req.put("msg","成功");
        log.info("验签成功");

        if (StringUtils.isEmpty(ordNo)) {
            log.info("实体卡微信充值订单号为空");
        }
        // 获取对应的充值订单，修改订单
        PhysicalCardBalance balance = new PhysicalCardBalance();
        balance.setBalanceNo(ordNo);
        PhysicalCardBalance physicalCardBalance = physicalCardBalanceService.selectPhysicalCardBalance(balance);
        log.info("实体卡微信充值回调订单信息,physicalCardBalance:[{}]",JSONObject.toJSONString(physicalCardBalance));
        if(Objects.isNull(physicalCardBalance) || StringUtils.isEmpty(physicalCardBalance.getPhysicalCardNo())){
            log.info("实体卡微信充值回调订单未找到 orderNo：[{}]",ordNo);
            throw new CustomException("实体卡微信充值回调订单未找到");
        }
        int i = physicalCardBalanceService.updatePhysicalCardBalance(physicalCardBalance);
        if(i <= 0){
            throw new CustomException("实体卡微信充值回调订单同步信息失败:" + JSONObject.toJSONString(physicalCardBalance));
        }

//        }else {
//            logger.info("验签失败");
//            req.put("code","fail");
//            req.put("msg","失败");
//        }
        log.info("返回随行付参数信息："+req.toString());
        return req;
    }



    /**
     * 储值卡云化支付回调接口
     * */
    @RequestMapping(value = "/yunHuaCard", consumes = "application/json", method = RequestMethod.POST)
    public void yunHuaCard(HttpServletRequest request, HttpServletResponse response) {
        // 接受异步消息
        try {
            // 获取当前请求的域名
            String reqPayType = request.getParameter("payType");
            String data = JKPayUtil.getParamByStream(request);
            log.info("云华开始充值回调" + data);
            JSONObject obj = JSON.parseObject(data);
            log.info("云华开始充值回调" + obj);

            String status = obj.getString("status");
            if ("3".equals(status)) { //验签成功

//                BigDecimal amt = obj.getBigDecimal("txnAmt");
                // 实体卡充值订单号
                String orderNo = obj.getString("clientSerialNo");
//                String payTime = obj.getString("payTime");
                String transPayNo = obj.getString("transPayNo");
                String translnfoNo = obj.getString("transInfoNo");
//                String payOrderNo = obj.getString("payOrderNo"); //商户订单号
//                String merchantDisAmt = obj.getString("merchantDisAmt");
//                String sponsorDisAmt = obj.getString("sponsorDisAmt");
//                String marketingDisAmt = obj.getString("marketingDisAmt");
//                String platformDisAmt = obj.getString("platformDisAmt");
//                String payAmt = obj.getString("payAmt");

                if (StringUtils.isEmpty(orderNo)) {
                    log.info("实体卡微信充值订单号为空");
                }
                // 获取对应的充值订单，修改订单
                PhysicalCardBalance balance = new PhysicalCardBalance();
                balance.setBalanceNo(orderNo);
                PhysicalCardBalance physicalCardBalance = physicalCardBalanceService.selectPhysicalCardBalance(balance);
                log.info("实体卡微信充值回调订单信息,physicalCardBalance:[{}]",JSONObject.toJSONString(physicalCardBalance));
                if(Objects.isNull(physicalCardBalance) || StringUtils.isEmpty(physicalCardBalance.getPhysicalCardNo())){
                    log.info("实体卡微信充值回调订单未找到 orderNo：[{}]",orderNo);
                    throw new CustomException("实体卡微信充值回调订单未找到");
                }
                physicalCardBalance.setTransactionId(transPayNo);
                physicalCardBalance.setMerchantsNumber(translnfoNo);
                int i = physicalCardBalanceService.updatePhysicalCardBalance(physicalCardBalance);
                if(i <= 0){
                    throw new CustomException("实体卡微信充值回调订单同步信息失败:" + JSONObject.toJSONString(physicalCardBalance));
                }

            }else {
                log.info("实体卡云化支付回调验签失败 status:[{}]",status);
            }

        }catch (Exception e) {
            log.info("实体卡云化支付回调错误日志+" + e.getMessage());
            e.printStackTrace();
        }
    }


    @PostMapping("/consumption")
    @ApiOperation(value = "实体卡消费",response = PhysicalCardSecretKeyDto.class)
    public ResultData consumption(@RequestBody PhysicalCardOrderDto physicalCardOrderDto){
        if(Objects.isNull(physicalCardOrderDto) || StringUtils.isEmpty(physicalCardOrderDto.getPhysicalCardNo())
                || StringUtils.isEmpty(physicalCardOrderDto.getMessage())){
            return ResultData.error("请求参数异常");
        }
        physicalCardOrderDto.setPhysicalCardNo(StringUtils.trim(physicalCardOrderDto.getPhysicalCardNo()));
        log.info("apipay 实体卡消费：[{}]",JSONObject.toJSONString(physicalCardOrderDto));
        // 密文校验
        if(!checkMessage(physicalCardOrderDto.getMessage())){
            return ResultData.error("密文校验失败");
        }
        if(Objects.isNull(physicalCardOrderDto.getAmount())){
            return ResultData.error("请输入消费金额");
        }
        if(Objects.isNull(physicalCardOrderDto.getConsumptionStationId())){
            return ResultData.error("请输入油站");
        }
        if(com.alibaba.druid.util.StringUtils.isEmpty(physicalCardOrderDto.getOilGun())){
            return ResultData.error("请输入油枪号");
        }
        if(com.alibaba.druid.util.StringUtils.isEmpty(physicalCardOrderDto.getOilPersonnelId())){
            return ResultData.error("请输入加油员");
        }

        PayOrder payOrder = physicalCardService.physicalCardConsumption(physicalCardOrderDto);
        log.info("poj机返回实体卡消费：[{}]",JSONObject.toJSONString(payOrder));
        PhysicalCardSecretKeyDto physicalCardSecretKeyDto = new PhysicalCardSecretKeyDto();
        BeanUtils.copyProperties(payOrder,physicalCardSecretKeyDto);
        physicalCardSecretKeyDto.setOilPirce(Objects.nonNull(payOrder.getOilPirce()) ? new BigDecimal(payOrder.getOilPirce()) : BigDecimal.ZERO);
        physicalCardSecretKeyDto.setOrderLiters(Objects.nonNull(payOrder.getOrderLiters()) ? new BigDecimal(payOrder.getOrderLiters()) : BigDecimal.ZERO);
        physicalCardSecretKeyDto.setAmt(Objects.nonNull(payOrder.getAmt()) ? BigDecimal.valueOf(payOrder.getAmt()) : BigDecimal.ZERO);
        physicalCardSecretKeyDto.setReceivableAmt(Objects.nonNull(payOrder.getReceivableAmt()) ? BigDecimal.valueOf(payOrder.getReceivableAmt()) : BigDecimal.ZERO);
        physicalCardSecretKeyDto.setDiscountAmt(Objects.nonNull(payOrder.getDiscountAmt()) ? BigDecimal.valueOf(payOrder.getDiscountAmt()) : BigDecimal.ZERO);
        physicalCardSecretKeyDto.setDiscountCouponAmt(Objects.nonNull(payOrder.getDiscountCouponAmt()) ? BigDecimal.valueOf(payOrder.getDiscountCouponAmt()) : BigDecimal.ZERO);
        physicalCardSecretKeyDto.setMobilePhone(payOrder.getCustomerPhone());
        physicalCardSecretKeyDto.setPhysicalCardNo(physicalCardOrderDto.getPhysicalCardNo());
        physicalCardSecretKeyDto.setSecretKeyA(SECRET_KEY_A);
        physicalCardSecretKeyDto.setPayTypeName("实体卡");

        return ResultData.success(physicalCardSecretKeyDto);
    }

    private boolean checkMessage(String message){
        String decrypt = "";
        try {
            decrypt = RSAUtils.decrypt(message, privateKey);
        } catch (Exception e){
            log.info("pos机密文校验失败：[{}]",e.getMessage());
            return false;
        }
        if(messageKey.equals(decrypt)){
            return true;
        }
        return false;
    }

}
